﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using S3.Biz;
using S3.Common;
using S3.DataModel;

namespace S3
{
    public partial class TransactionHistoryGame : S3FormBase
    {
        public TransactionHistoryGame()
        {
            InitializeComponent();
            //ConfigSecurity();
            InitConfig();
            LoadData();
        }

        //Callback by Login form
        public void ConfigSecurity()
        {
            using (var manager = new UserManager())
            {
                User user = manager.GetOne(Constants.StaffName);
                if (user != null)
                {
                    //Cau hinh cho Admin
                    if (user.Role.ToLower() == UserRoleValue.Text[UserRole.Admin].ToLower())
                    {
                        lblTotalMoney.Visible = true;
                        label6.Visible = true;
                        chkSelectAll.Visible = true;
                        lblTotalTime.Visible = true;
                        lblTotalGameMoney.Visible = true;
                        lblTotalServiceMoney.Visible = true;
                        //lblTotalPaidHelp.Visible = true;
                        //lblTotalMoneyByDesk.Visible = true;
                        btnDelete.Visible = true;
                    }

                    //Cai hinh cho Nhan vien
                    if (user.Role.ToLower() == UserRoleValue.Text[UserRole.Staff].ToLower())
                    {
                        lblTotalMoney.Visible = false;
                        label6.Visible = false;
                        chkSelectAll.Visible = false;
                        lblTotalTime.Visible = false;
                        lblTotalGameMoney.Visible = false;
                        lblTotalServiceMoney.Visible = false;
                        //lblTotalPaidHelp.Visible = false;
                        //lblTotalMoneyByDesk.Visible = false;
                        btnDelete.Visible = false;
                    }
                }
            }
        }

        private void InitConfig()
        {
            //gridGameHistory.AutoGenerateColumns = false;
            //System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("vi");
            //System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture;

            //Application.CurrentCulture = new CultureInfo("vi-VN");
            //dtPickerFrom.Format = DateTimePickerFormat.Custom;
            dtPickerFrom.Properties.DisplayFormat.FormatString = Constants.Format_DateTime_Hour;
                // "dd/MM/yyyy HH:mm";// Application.CurrentCulture.DateTimeFormat.ShortDatePattern;
            //dtPickerTo.Format = DateTimePickerFormat.Custom;
            dtPickerTo.Properties.DisplayFormat.FormatString = Constants.Format_DateTime_Hour;

            //Set default value
            DateTime currentDate = DateTime.Now;
            //set from date is smaller than current date 24 hours
            DateTime fromDate = currentDate.AddDays(-1);
            dtPickerFrom.DateTime = fromDate;
            dtPickerTo.DateTime = currentDate;

            var minDate = new DateTime(2010, 01, 01);
            dtPickerFrom.Properties.MinValue = minDate;
            dtPickerTo.Properties.MinValue = minDate;

            gridGameHistory.AutoGenerateColumns = false;
            using (var manager = new TimingServiceConfigurationManager())
            {
                IEnumerable<string> deskList = manager.GetAllDesks().Select(a => a.TimingServiceName);

                comboDesks.Items.Clear();
                comboDesks.Items.Add("++ Tất cả ++");
                foreach (string item in deskList)
                {
                    comboDesks.Items.Add(item);
                }

                comboDesks.SelectedIndex = 0;
            }
        }

        private void LoadData()
        {
            DateTime selectedDateFrom = dtPickerFrom.DateTime;
            DateTime selectedDateTo = dtPickerTo.DateTime;
            string deskName = comboDesks.SelectedItem + "";

            using (var dailyEntryManager = new DailyTimingEntryManager())
            {
                IQueryable<DailyTimingEntry> list =
                    dailyEntryManager.GetFinishedDesks().Where(
                        a =>
                        a.EndTime != null && (a.EndTime.Value.CompareTo(selectedDateFrom) > 0 &&
                                              a.EndTime.Value.CompareTo(selectedDateTo) <= 0));

                if (comboDesks.SelectedIndex > 0)
                {
                    list = list.Where(a => a.TimingServiceName.ToLower() == deskName.ToLower());
                }

                list = list.OrderByDescending(a => a.EndTime != null ? a.EndTime.Value : new DateTime());

                //Define
                var extendDailyEntryList = new List<ExtendDailyEntry>();
                decimal moneyTotal = 0;
                decimal totalTime = 0;
                decimal moneyService = 0;
                decimal moneyByDesk = 0;
                decimal moneyPaidHelp = 0;
                decimal moneyGame = 0;

                foreach (DailyTimingEntry item in list)
                {
                    decimal subGameMoney = 0;
                    subGameMoney = item.Amount - item.Amount;// +item.Paid;

                    var entry = new ExtendDailyEntry
                                    {
                                        DailyTimingEntryID = item.DailyTimingEntryID,
                                        TimingServiceName = item.TimingServiceName,
                                        EndTime =
                                            item.EndTime.HasValue
                                                ? string.Format(Constants.Format_Date_Time, item.EndTime)
                                                : "",
                                        Type = item.Type,
                                        Notes = item.Notes,
                                        StartTime = string.Format(Constants.Format_Date_Time, item.StartTime),
                                        TotalMoney = Utils.StringFormatMoney(item.Amount),
                                        //Paid = Utils.StringFormatMoney(item.Paid),
                                        StaffName = item.StaffName,
                                        SessionBy =
                                            string.IsNullOrEmpty(item.SessionBy) ? "(Chưa bàn giao)" : item.SessionBy,
                                        ServiceMoney = Utils.StringFormatMoney(item.Amount),
                                        GameMoney = Utils.StringFormatMoney(subGameMoney)
                                    };

                    if (item.EndTime.HasValue)
                    {
                        decimal totalSubTime =
                            Convert.ToDecimal(item.EndTime.Value.Subtract(item.StartTime).TotalMinutes);
                        if (totalSubTime < 1)
                        {
                            totalSubTime = 1;
                        }

                        totalTime = totalTime + totalSubTime;

                        entry.TotalTime = Utils.StringFormatMoney(totalSubTime);
                    }

                    extendDailyEntryList.Add(entry);

                    //calculate sub total
                    moneyGame = moneyGame + subGameMoney;
                    moneyByDesk = moneyByDesk + item.Amount;
                    moneyService = moneyService + item.Amount;
                    moneyPaidHelp = moneyPaidHelp;// +item.Paid;
                    moneyTotal = moneyTotal + moneyByDesk + moneyPaidHelp;
                }

                //Display grid
                gridGameHistory.DataSource = extendDailyEntryList;

                //Display total                
                lblTotalTime.Text = Utils.StringFormatMoney(totalTime);
                lblTotalGameMoney.Text = Utils.StringFormatMoney(moneyGame);
                lblTotalServiceMoney.Text = Utils.StringFormatMoney(moneyService);
                //lblTotalPaidHelp.Text = Utils.StringFormatMoney(moneyPaidHelp);
                //lblTotalMoneyByDesk.Text = Utils.StringFormatMoney(moneyByDesk);
                lblTotalMoney.Text = Utils.StringFormatMoney(moneyPaidHelp + moneyByDesk);
                lblTransactionCount.Text = list.Count() + "";
            }
        }

        private void BtnViewClick(object sender, EventArgs e)
        {
            LoadData();
        }

        private void DtPickerToValueChanged(object sender, EventArgs e)
        {
            //Neu ngay bat dau lon hon ngay ket thuc
            if (dtPickerFrom.DateTime.CompareTo(dtPickerTo.DateTime) > 0)
            {
                dtPickerFrom.DateTime = dtPickerTo.DateTime.AddDays(-1);
            }

            //Set max date of From is current To date.
            dtPickerFrom.Properties.MaxValue = dtPickerTo.DateTime;
        }

        private void BtnDeleteClick(object sender, EventArgs e)
        {
            if (gridGameHistory.SelectedRows.Count > 0)
            {
                if (XtraMessageBox.Show("Bạn thực sự muốn xóa (các) giao dịch này?", "Chú ý", MessageBoxButtons.YesNo) ==
                    DialogResult.Yes)
                {
                    var strID = new StringBuilder();
                    foreach (DataGridViewRow row in gridGameHistory.SelectedRows)
                    {
                        strID.Append(row.Cells["ID"].Value);
                        strID.Append(";");
                    }

                    var dailyEntryManager = new DailyTimingEntryManager();
                    dailyEntryManager.Delete(strID.ToString());

                    //Reload data
                    LoadData();
                }
            }
            else
            {
                XtraMessageBox.Show("Vui lòng chọn giao dịch bạn muốn xóa !");
            }
        }

        private void btnSelectAll_Click(object sender, EventArgs e)
        {
            gridGameHistory.SelectAll();
        }

        private void BtnCloseClick(object sender, EventArgs e)
        {
            Close();
        }

        private void ChkSelectAllCheckedChanged(object sender, EventArgs e)
        {
            if (chkSelectAll.Checked)
            {
                gridGameHistory.SelectAll();
            }
            else
            {
                if (gridGameHistory.Rows.Count > 0)
                {
                    foreach (DataGridViewRow row in gridGameHistory.SelectedRows)
                    {
                        row.Selected = false;
                    }

                    gridGameHistory.Rows[0].Selected = true;
                }
            }
        }

        #region ProcessCmdKey

        /// <summary>
        /// Close form if click ESC
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="keyData"></param>
        /// <returns></returns>
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            try
            {
                if (msg.WParam.ToInt32() == (int) Keys.Escape)
                {
                    Close();
                }
                else
                {
                    return base.ProcessCmdKey(ref msg, keyData);
                }
            }
            catch (Exception Ex)
            {
                XtraMessageBox.Show("Key Overrided Events Error:" + Ex.Message);
            }

            return base.ProcessCmdKey(ref msg, keyData);
        }

        #endregion
    }
}